package de.tabuma.lib.webservice.wsdl;

import java.lang.reflect.*;
import java.util.*;
import java.util.logging.*;

/**
 *
 * @author alefen
 */
public class BindingFacade {

    private static final Logger log = Logger.getLogger(BindingFacade.class.getName());

    public static String getBinding(Hashtable<String,Class> methodTable) {
        String str = "";
        Enumeration<String> keys = methodTable.keys();
        while(keys.hasMoreElements()) {
            String key = keys.nextElement();
            Class clazz = methodTable.get(key);
            str += "<binding name=\""+key+"Binding\" type=\"tns:"+key+"PortType\">\n";
            str += "<soap:binding style=\"rpc\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n";
            for(int i=0;i<clazz.getDeclaredMethods().length;i++) {
                Method method = clazz.getDeclaredMethods()[i];
                str += getOperation(key, method);
            }
            str += "</binding>\n";
        }
        return str;
    }

    
    public static String getOperation(String name, Method method) {
        String str = "";
        str += "<operation name=\""+name+"_"+method.getName()+"\">\n";
        str += "<soap:operation soapAction=\""+name+"_"+method.getName()+"\"/>\n";
        str += getInput(name, method);
        str += getOutput(name, method);
        str += getFault(name, method);
        str += "</operation>\n";
        return str;
    }

    public static String getInput(String name, Method method) {
        String str = "";
        str += "<input name=\""+name+"_"+method.getName()+"_input\">\n";
        str += "<soap:body use=\"literal\"/>\n";
        str += "</input>";
        return str;
    }

    public static String getOutput(String name, Method method) {
        String str = "";
        if(!method.getReturnType().getName().equals("void")) {
            str += "<output name=\""+name+"_"+method.getName()+"_output\">\n";
            str += "<soap:body use=\"literal\"/>\n";
            str += "</output>";
        }
        return str;
    }

    public static String getFault(String name, Method method) {
        String str = "";
        if(!method.getReturnType().getName().equals("void")) {
            str += "<fault name=\""+name+"_"+method.getName()+"_exception\">\n";
            str += "<soap:fault use=\"literal\" name=\""+name+"_"+method.getName()+"_exception\"/>\n";
            str += "</fault>";
        }
        return str;
    }
}
